package org.example;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter.Feature;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    private static final String USER_NAME_PRE = "测试名称 c++/go/cangjie 编程语言 json序列化、反序列化性能大比拼 - ";

    private static final float SCORE_BASE = 65.5f;

    private static final int AGE_BASE = 18;

    private static final String JSON_STR;

    private Response res;

    static {
        JSON.config(Feature.LargeObject, Boolean.TRUE);
        int num = 1000000;
        Stu[] stuSlice = new Stu[num];
        for (int i = 0; i < num; i++) {
            Stu tmpStu = new Stu(USER_NAME_PRE + i, i % 2, AGE_BASE + i, SCORE_BASE + i);
            stuSlice[i] = tmpStu;
        }
        JSON_STR = JSON.toJSONString(new Response(200, "成功", stuSlice));
    }

    @Benchmark
    public void testJsonDecode() {
        res = JSON.parseObject(JSON_STR, Response.class);
    }

    @TearDown(Level.Iteration)
    public void showRes() {
        System.out.printf("json字符串反序列化后信息——code：%d, msg:%s, listLen: %d\t耗时：", res.code, res.msg, res.list.length);
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}